package com.ruowei.modules.foodOrder.service;

import com.ruowei.modules.foodOrder.domain.PaymentFlow;
import com.ruowei.modules.foodOrder.domain.enumeration.FlowType;
import com.ruowei.modules.foodOrder.repository.PaymentFlowRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;

@Service
@Slf4j
public class PaymentFlowService {
    private final PaymentFlowRepository paymentFlowRepository;

    public PaymentFlowService(PaymentFlowRepository paymentFlowRepository) {
        this.paymentFlowRepository = paymentFlowRepository;
    }

    public void savePaymentFlow(String orderCode, String orderReturnCode, String memberCode,
                                FlowType type, String merchantCode, String merchantName, BigDecimal amount) {
        if (!paymentFlowRepository.findFirstByOrderCodeAndTypeOrderByTimeDesc(orderCode, type).isPresent()) {
            PaymentFlow flow = new PaymentFlow();
            flow.setOrderCode(orderCode);
            flow.setOrderReturnCode(orderReturnCode);
            flow.setMemberCode(memberCode);
            flow.setType(type);
            flow.setDate(LocalDate.now());
            flow.setTime(Instant.now());
            flow.setMerchantCode(merchantCode);
            flow.setMerchantName(merchantName);
            flow.setAmount(amount);
            paymentFlowRepository.saveAndFlush(flow);
        }
    }
}
